/**
 * 剑指 Offer 52. 两个链表的第一个公共节点
 * https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/
 */

/**
 * @param {ListNode} headA
 * @param {ListNode} headB
 * @return {ListNode}
 */
function getIntersectionNode(headA, headB) {
  if (!headA || !headB) {
    return null;
  }
  let node1 = headA;
  let node2 = headB;
  while (node1 && node2) {
    if (node1 === node2) {
      return node1;
    }
    node1 = node1.next;
    node2 = node2.next;
  }
  if (!node1 && !node2) {
    return null;
  }
  let longer;
  let shorter;
  if (node1) {
    longer = headA;
    shorter = headB;
  } else {
    longer = headB;
    shorter = headA;
    node1 = node2;
  }
  node2 = longer;
  while (node1) {
    node1 = node1.next;
    node2 = node2.next;
  }
  node1 = shorter;
  while (node1 !== node2) {
    node1 = node1.next;
    node2 = node2.next;
  }
  return node1;
}

console.log(getIntersectionNode(null, null) === null);
